import React, {useState} from 'react';
import {View, Text, Button} from 'react-native';

// 定义子组件接收的props类型
interface ChildProps {
  name: string;
  age: number;
  score: number;
  hobbies: string[];
  onUpdateAge: () => void;
  onUpdateScore: (newScore: number) => void;
}

// 父组件
export default function App() {
  // 在父组件中维护多个状态
  const [name] = useState('张三');
  const [age, setAge] = useState(25);
  const [score, setScore] = useState(85);
  const [hobbies] = useState(['阅读', '游泳', '编程']);

  // 处理年龄更新
  const handleAgeUpdate = () => {
    setAge(age + 1);
  };

  // 处理分数更新
  const handleScoreUpdate = (newScore: number) => {
    setScore(newScore);
  };

  // 解构传递多个属性和方法
  const childProps = {
    name,
    age,
    score,
    hobbies,
    onUpdateAge: handleAgeUpdate,
    onUpdateScore: handleScoreUpdate,
  };

  return (
    <View>
      <Text>父组件</Text>
      <Text>
        姓名: {name}, 年龄: {age}, 分数: {score}
      </Text>

      {/* 方式1: 逐个传递属性 */}
      <Child
        name={name}
        age={age}
        score={score}
        hobbies={hobbies}
        onUpdateAge={handleAgeUpdate}
        onUpdateScore={handleScoreUpdate}
      />

      {/* 方式2: 使用展开运算符传递所有属性 */}
      <Child {...childProps} />
    </View>
  );
}

// 子组件 - 通过解构直接获取所需的属性
const Child: React.FC<ChildProps> = ({
  name,
  age,
  score,
  hobbies,
  onUpdateAge,
  onUpdateScore,
}) => {
  return (
    <View>
      <Text>子组件</Text>
      <Text>姓名: {name}</Text>
      <Text>年龄: {age}</Text>
      <Text>分数: {score}</Text>
      <Text>爱好: {hobbies.join(', ')}</Text>

      <Button title="增加年龄" onPress={onUpdateAge} />

      <Button title="提高分数" onPress={() => onUpdateScore(score + 5)} />
    </View>
  );
};
